//
//  PCJoinPhotoMatchUploadVC.m
//  PhotoCircle
//
//  Created by wujungao on 12/20/15.
//  Copyright © 2015 wujungao. All rights reserved.
//

#import "PCJoinPhotoMatchUploadVC.h"
#import "PCMeStore.h"
#import "GMTipsHelper.h"
#import "PCUserInfoManager.h"
#import "PCUserModel.h"
#import "PCUserLoginViewController.h"
#import "GMString.h"
#import <ImageIO/ImageIO.h>
#import <AssetsLibrary/AssetsLibrary.h>

#import "PCOpusDetailVC.h"
#define INVALIDTOKEN   20000

@interface PCJoinPhotoMatchUploadVC ()<UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;

- (IBAction)backBtnAction:(UIButton *)sender;
- (IBAction)sureBtnAction:(UIButton *)sender;

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UITextField *opusName;
@property (weak, nonatomic) IBOutlet UITextField *authorName;
@property (weak, nonatomic) IBOutlet UITextField *opusBrief;
//@property (weak, nonatomic) IBOutlet UITextField *authorName;
//@property (weak, nonatomic) IBOutlet UITextView *note;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewBottomConstraint;
@property(nonatomic,strong)UIImage *image;
@property(nonatomic,strong)NSDictionary *imageMetaData;
@property(nonatomic,strong)NSString *promptMsg;
@property(nonatomic,strong)NSString *token;
@property(nonatomic,assign)BOOL giveupFlag;
@property(nonatomic,strong)NSString *uuid;

@end

@implementation PCJoinPhotoMatchUploadVC

#pragma mark - PCJoinPhotoMatchUploadVC method

- (void) keyboardWasShown:(NSNotification *) notif
{
    //self.scrView_background.scrollEnabled = NO;
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    [UIView animateWithDuration:0.3 animations:^(){
        //self.scrView_background.contentOffset = CGPointMake(0, 85);
        self.viewBottomConstraint.constant = keyboardSize.height;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished){
    }];
}

- (void) keyboardWasHidden:(NSNotification *) notif
{
    //self.scrView_background.scrollEnabled = YES;
    [UIView animateWithDuration:0.3 animations:^(){
        //self.scrView_background.contentOffset = CGPointMake(0, 0);
        self.viewBottomConstraint.constant = 0;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished){
    }];
}

#pragma mark - 观察中心
- (void) changeInputMode:(NSNotification *)notif{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    if (self.viewBottomConstraint.constant!=0) {
        [UIView animateWithDuration:0.2 animations:^(){
            self.viewBottomConstraint.constant = keyboardSize.height;
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished){
        }];
    }
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
}

-(void)configUI
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapView)];
    [self.scrollView addGestureRecognizer:tap];
    
    //使用NSNotificationCenter 键盘出现时
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
    //使用NSNotificationCenter 键盘隐藏时
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil];
    //使用NSNotificationCenter 键盘出输入法改变时现时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeInputMode:) name:UIKeyboardDidChangeFrameNotification object:nil];
}

-(void)tapView
{
    [self.opusName resignFirstResponder];
    [self.authorName resignFirstResponder];
    [self.opusBrief resignFirstResponder];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.imageView.image=self.image;
    [self configUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)passImage:(UIImage *)image withImageMetaDat:(NSDictionary *)imageMetaData{
    
    self.image=image;
    self.imageMetaData=imageMetaData;
}

-(void)tipAlertView
{
    if (iOS(8.0)) {
        
        UIAlertController * cancleAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的账号已在其他设备登录，是否重新登录?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAciton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[PCUserInfoManager sharedUserInfo] cleanLocalUserInfo];
            //跳转到个人中心
            [self jumpToLogin];
        }];
        
        UIAlertAction *cancleAcion = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [cancleAlert addAction:okAciton];
        [cancleAlert addAction:cancleAcion];
        [self presentViewController:cancleAlert animated:YES completion:^{
        }];
    }else{
        
        UIAlertView *cancleAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否删除图片" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        //cancleAlert.tag =CancleTag;
        cancleAlert.delegate = self;
        cancleAlert.tag = INVALIDTOKEN;
        [cancleAlert show];
    }
}

#pragma mark - button Action
- (IBAction)backBtnAction:(UIButton *)sender {
    
    [GMTipsHelper showDismiss];
    self.promptMsg=@"放弃参赛";
    self.giveupFlag=YES;
    [self loginPrompt];
}

- (IBAction)sureBtnAction:(UIButton *)sender {
    
    [self upLoadImage:self.image];
}

-(void)upLoadImage:(UIImage *)image{
    
    self.token=([[PCUserInfoManager  sharedUserInfo] readUserInfo]).userToken;
    
    if([NSString isEmptyString:self.token]){
        
        self.promptMsg=@"请登录";
        [self loginPrompt];
        return;
        
    }else if([NSString isEmptyString:self.opusName.text]){
        
        self.promptMsg=@"请填写作品名称";
        [self loginPrompt];
        return;
        
    }else if([NSString isEmptyString:self.opusBrief.text]){
        
        self.promptMsg=@"请填写作品简介";
        [self loginPrompt];
        return;
        
    }else if([NSString isEmptyString:self.authorName.text]){
        
        self.promptMsg=@"请填写作者姓名";
        [self loginPrompt];
        return;
    }
    
    NSDictionary *dictionary;
    
    if(![NSString isEmptyString:self.opusName.text] && ![NSString isEmptyString:self.opusBrief.text] && ![NSString isEmptyString:self.authorName.text]){
        
        dictionary=@{@"token":self.token,@"title":self.opusName.text,@"desc":self.opusBrief.text,@"user_name":self.authorName.text};
    }
    
    UIImage *newImage=[self compressImageToTargetSize:self.image];
    NSData *compressedImageData = [self compressImageWith:newImage];
    NSData *saveMetaDataImageData=[self saveMetaDataWithImageData:compressedImageData andMetaData:self.imageMetaData];
    [GMTipsHelper showLoading];
    
    [[PCMeStore sharedMeStore] uploadPhotoForJoinMatch:dictionary image:saveMetaDataImageData successHandler:^(NSInteger responCode,NSString *uuid){
        if (responCode == API_RESPONSE_OK) {
            
            [GMTipsHelper showSuccess:@"上传成功"];
            self.uuid=uuid;
            [self performSelector:@selector(popViewController) withObject:nil afterDelay:0.8];;

        }else if(responCode == API_RESPONSE_INVALIDTOKEN){
            // 加载
            [GMTipsHelper showDismiss];
            [self tipAlertView];
        }else{
            
            [GMTipsHelper showFail:@"上传失败"];
        }
    } errorHandler:^{
        
        [GMTipsHelper showBadNetwork];
    }];
}

-(void)popViewController
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    if([NSString isEmptyString:self.uuid]){
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        
        //跳转到作品详情页面
        UIStoryboard *stb=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        PCOpusDetailVC *opusDetailVC=[stb instantiateViewControllerWithIdentifier:@"PCOpusDetailVC"];
        opusDetailVC.workUuid=self.uuid;//uuid
        
        [self.navigationController pushViewController:opusDetailVC animated:YES];
    }
}

-(void)loginPrompt{
    
    if (iOS(8.0)) {
        
        UIAlertController * cancleAlert = [UIAlertController alertControllerWithTitle:@"提示" message:self.promptMsg preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAciton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //跳转到个人中心
            if([NSString isEmptyString:self.token] && self.giveupFlag!=YES){
                [self jumpToLogin];
            }else if(self.giveupFlag==YES){
                [self goBack];
            }
            
        }];
        
        UIAlertAction *cancleAcion = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [cancleAlert addAction:okAciton];
        [cancleAlert addAction:cancleAcion];
        [self presentViewController:cancleAlert animated:YES completion:^{
        }];
    }else{
        
        UIAlertView *cancleAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:self.promptMsg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        //cancleAlert.tag =CancleTag;
        cancleAlert.delegate = self;
        [cancleAlert show];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == INVALIDTOKEN) {
        if (buttonIndex == 0) {
            [[PCUserInfoManager sharedUserInfo] cleanLocalUserInfo];
            //跳转到个人中心
            [self jumpToLogin];

        }else{
        }
    }else{
        if (buttonIndex == 0) {
            //跳转到个人中心
            if([NSString isEmptyString:self.token] && self.giveupFlag!=YES){
                
                [self jumpToLogin];
                
            }else if(self.giveupFlag==YES){
                
                [self goBack];
            }
        }
    }
}

-(void)jumpToLogin{
    
    UIStoryboard *loginS=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];;
    PCUserLoginViewController *loginVC=[loginS instantiateViewControllerWithIdentifier:@"PCUserLoginVC"];
    //
    [self.navigationController pushViewController:loginVC animated:YES];
}

-(void)goBack{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - image Process
-(NSData *)compressImageWith:(UIImage *)image{
    
    CGFloat compressionQuality=9.0;
    NSData *imageData=UIImageJPEGRepresentation(image, compressionQuality);
    
    if(imageData.length/1024 > 1000){
        
        imageData=UIImageJPEGRepresentation(image, compressionQuality-0.4);
    }
    
    return imageData;
}

-(NSData *)saveMetaDataWithImageData:(NSData *)imageData andMetaData:(NSDictionary *)imageMetaData{
    
    CGImageSourceRef imageSource=CGImageSourceCreateWithData((__bridge CFDataRef)(imageData),NULL);
    CFStringRef UTI = CGImageSourceGetType(imageSource);
    
    NSMutableData *newImageData = [NSMutableData data];
    CGImageDestinationRef destination = CGImageDestinationCreateWithData(( CFMutableDataRef)newImageData, UTI, 1, NULL);
    CGImageDestinationAddImageFromSource(destination, imageSource, 0, ( CFDictionaryRef) imageMetaData);
    BOOL success = CGImageDestinationFinalize(destination);
    //    //test
    //    CGImageSourceRef newImageSource=CGImageSourceCreateWithData((__bridge CFDataRef)(newImageData),NULL);
    //    //test
    return newImageData;
}

-(UIImage *)compressImageToTargetSize:(UIImage *)image{
    
    CGFloat max=1000.0;
    CGSize imageSize=image.size;
    CGFloat ratio=imageSize.width/imageSize.height;
    
    CGFloat newH=ratio>1.0 ? max * ratio : max;
    CGFloat newW=ratio<1.0 ? max * ratio : max;
    
    UIGraphicsBeginImageContext(CGSizeMake(newW, newH));
    [image drawInRect:CGRectMake(0, 0, newW, newH)];
    
    UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
    
    return newImage;
}

@end
